package com.zys.controller;

import com.zys.entity.Result;
import com.zys.pojo.Category;
import com.zys.service.CateService;
import com.zys.constant.MessageConstant;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 处理分类相关操作
 */
@RestController
@RequestMapping("/category")
public class CateController {

  @Reference
  private CateService cateService;

  /**
   * 查询所有的分类列表
   *
   * @return Result
   */
  @RequestMapping("/findAll")
  public Result findAll() {
    try {
      return new Result(true, MessageConstant.GET_CATEGORY_LIST_SUCCESS, cateService.findAll());
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.GET_CATEGORY_LIST_FAIL);
    }
  }

  /**
   * 添加分类
   *
   * @param category 分类信息
   * @return Result
   */
  @RequestMapping("/add")
  public Result add(@RequestBody Category category) {
    try {
      cateService.add(category);
      return new Result(true, MessageConstant.ADD_CATEGORY_SUCCESS);
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.ADD_CATEGORY_FAIL);
    }
  }

  /**
   * 根据 id 查询分类信息
   *
   * @param id 分类 id
   * @return Result
   */
  @RequestMapping("/getCateById")
  public Result getCateById(Integer id) {
    try {
      return new Result(true, MessageConstant.GET_CATEGORY_SUCCESS, cateService.findCateById(id));
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.GET_CATEGORY_FAIL);
    }
  }

  /**
   * 根据 id 删除分类信息
   *
   * @param id 分类 id
   * @return Result
   */
  @RequestMapping("/delete")
  public Result delete(Integer id) {
    try {
      cateService.delete(id);
      return new Result(true, MessageConstant.DELETE_CATEGORY_SUCCESS);
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.DELETE_CATEGORY_FAIL);
    }
  }

  /**
   * 修改分类信息
   *
   * @param category 分类信息
   * @return Result
   */
  @RequestMapping("/edit")
  public Result edit(@RequestBody Category category) {
    try {
      cateService.edit(category);
      return new Result(true, MessageConstant.EDIT_CATEGORY_SUCCESS);
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.EDIT_CATEGORY_FAIL);
    }
  }
}
